<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Store;
use App\Models\StoreCategory;
use App\Models\StoreGoods;
use Illuminate\Http\Request;
use App\Services\ImageUrlService;
use Exception;

class MerchantApiController extends BaseApiController
{
    /**
     * 获取商家详情
     */
    public function detail(Request $request)
    {
        try {
            // 获取参数
            $storeId = $this->getParam($request, 'store_id') ?: $this->getParam($request, 'id');
            
            if (!$storeId) {
                return response()->json([
                    'code' => 400,
                    'message' => '商家ID不能为空',
                    'data' => null
                ]);
            }

            // 查询商家信息
            $store = Store::with(['category', 'storeGoods.goods'])
                ->where('id', $storeId)
                ->where('is_hide', 0)
                ->first();

            if (!$store) {
                return response()->json([
                    'code' => 404,
                    'message' => '商家不存在',
                    'data' => null
                ]);
            }

            // 获取商家分类信息
            $category = $store->category;
            
            // 查询一级分类下的所有二级分类
            $secondCategories = collect();
            if ($category) {
                $secondCategories = StoreCategory::where('parent_id', $category->id)
                    ->where('is_open', 1)
                    ->orderBy('sort', 'asc')
                    ->get(['id', 'name']);
            }

            // 查询该分类下的商品列表
            $goodsQuery = StoreGoods::with(['goods'])
                ->where('store_id', $storeId)
                ->whereHas('goods', function($query) use ($category) {
                    if ($category) {
                        $query->where('goods_gift', 1); // 使用goods_gift字段
                    }
                });

            $goods = $goodsQuery->paginate(15);

            // 构建first_category数据结构
            $firstCategoryData = null;
            if ($category) {
                $firstCategoryData = [
                    'first_category' => [
                        [
                            'id' => $category->id,
                            'name' => $category->name
                        ]
                    ],
                    'second_category' => $secondCategories->map(function($item) {
                        return [
                            'id' => $item->id,
                            'name' => $item->name
                        ];
                    })->toArray(),
                    'goods' => [
                        'current_page' => $goods->currentPage(),
                        'data' => $goods->items()->map(function($storeGoods) use ($store) {
                            $goods = $storeGoods->goods;
                            if (!$goods) return null;
                            
                            return [
                                'id' => $goods->id,
                                'uniacid' => $goods->uniacid ?? 1,
                                'brand_id' => $goods->brand_id ?? 0,
                                'type' => $goods->type ?? 1,
                                'status' => $goods->status ?? 1,
                                'display_order' => $goods->display_order ?? 0,
                                'title' => $goods->title ?? '',
                                'thumb' => ImageUrlService::processImageUrl($goods->thumb),
                                'thumb_url' => 'a:0:{}',
                                'sku' => $goods->sku ?? '',
                                'description' => $goods->description ?? '',
                                'content' => $goods->content ?? '',
                                'goods_sn' => $goods->goods_sn ?? '',
                                'product_sn' => $goods->product_sn ?? '',
                                'market_price' => $goods->market_price ?? '0.00',
                                'price' => $goods->price ?? '0.00',
                                'cost_price' => $goods->cost_price ?? '0.00',
                                'stock' => $goods->stock ?? 0,
                                'reduce_stock_method' => $goods->reduce_stock_method ?? 0,
                                'show_sales' => $goods->show_sales ?? 0,
                                'real_sales' => $goods->real_sales ?? 0,
                                'weight' => $goods->weight ?? '0.00',
                                'has_option' => $goods->has_option ?? 0,
                                'is_new' => $goods->is_new ?? 0,
                                'is_hot' => $goods->is_hot ?? 0,
                                'is_discount' => $goods->is_discount ?? 0,
                                'is_recommand' => $goods->is_recommand ?? 0,
                                'is_comment' => $goods->is_comment ?? 0,
                                'is_deleted' => $goods->is_deleted ?? 0,
                                'created_at' => $goods->created_at ? $goods->created_at->format('Y-m-d H:i:s') : '',
                                'deleted_at' => $goods->deleted_at,
                                'updated_at' => $goods->updated_at ? $goods->updated_at->format('Y-m-d H:i:s') : '',
                                'comment_num' => $goods->comment_num ?? 0,
                                'is_plugin' => $goods->is_plugin ?? 0,
                                'plugin_id' => $goods->plugin_id ?? 0,
                                'virtual_sales' => $goods->virtual_sales ?? 0,
                                'no_refund' => $goods->no_refund ?? 0,
                                'need_address' => $goods->need_address ?? 0,
                                'type2' => $goods->type2 ?? 1,
                                'old_id' => $goods->old_id,
                                'volume' => $goods->volume,
                                'alias' => $goods->alias ?? '',
                                'award_user' => $goods->award_user,
                                'award_type' => $goods->award_type ?? 0,
                                'agent_one' => $goods->agent_one ?? '0.00',
                                'agent_two' => $goods->agent_two ?? '0',
                                'agent_three' => $goods->agent_three ?? '0',
                                'add_one' => $goods->add_one ?? '0.00',
                                'add_two' => $goods->add_two ?? '0.00',
                                'add_three' => $goods->add_three ?? '0.00',
                                'add_type' => $goods->add_type ?? 0,
                                'new_member' => $goods->new_member,
                                'sc_level' => $goods->sc_level ?? 0,
                                'is_sc_level' => $goods->is_sc_level ?? 0,
                                'fenzu_ids' => $goods->fenzu_ids,
                                'zt_one' => $goods->zt_one ?? '0.00',
                                'zt_two' => $goods->zt_two ?? '0.00',
                                'zt_three' => $goods->zt_three ?? '0.00',
                                'vendor_id' => $goods->vendor_id,
                                'goods_category_id' => $goods->goods_category_id ?? 0,
                                'goods_id' => $goods->id,
                                'category_id' => $goods->category_id ?? 0,
                                'category_ids' => $goods->category_ids ?? '',
                                'buyNum' => 0,
                                'reserve_goods' => false,
                                'vip_level_status' => [
                                    'status' => 0,
                                    'word' => '',
                                    'tips' => ''
                                ],
                                'goods_content_show' => $goods->goods_content_show,
                                'store_name' => $store->store_name,
                                'store_id' => $store->id,
                                'change_thumb' => ImageUrlService::processImageUrl($goods->thumb),
                                'has_many_specs' => [],
                                'has_many_options' => [],
                                'has_one_store_goods' => [
                                    'id' => $storeGoods->id,
                                    'goods_id' => $storeGoods->goods_id,
                                    'store_id' => $storeGoods->store_id,
                                    'created_at' => $storeGoods->created_at ? $storeGoods->created_at->format('Y-m-d H:i:s') : '',
                                    'updated_at' => $storeGoods->updated_at ? $storeGoods->updated_at->format('Y-m-d H:i:s') : '',
                                    'deleted_at' => $storeGoods->deleted_at,
                                    'goods_gift' => $storeGoods->goods_gift ?? 0,
                                    'customer_development' => $storeGoods->customer_development ?? 0,
                                    'has_one_optimization_store' => [
                                        'id' => $store->id,
                                        'uniacid' => $store->uniacid ?? 1,
                                        'uid' => $store->uid ?? 0,
                                        'store_name' => $store->store_name,
                                        'thumb' => ImageUrlService::processImageUrl($store->thumb),
                                        'category_id' => $store->category_id ?? 0,
                                        'province_id' => $store->province_id ?? 0,
                                        'city_id' => $store->city_id ?? 0,
                                        'district_id' => $store->district_id ?? 0,
                                        'street_id' => $store->street_id ?? 0,
                                        'address' => $store->address ?? '',
                                        'longitude' => $store->longitude ?? 0,
                                        'latitude' => $store->latitude ?? 0,
                                        'mobile' => $store->mobile ?? '',
                                        'store_introduce' => $store->store_introduce ?? '',
                                        'username' => $store->username ?? '',
                                        'password' => $store->password ?? '',
                                        'template_id' => $store->template_id ?? '',
                                        'salers' => 'a:0:{}',
                                        'cashier_id' => $store->cashier_id ?? 0,
                                        'created_at' => $store->created_at ? $store->created_at->format('Y-m-d H:i:s') : '',
                                        'updated_at' => $store->updated_at ? $store->updated_at->format('Y-m-d H:i:s') : '',
                                        'deleted_at' => $store->deleted_at,
                                        'business_hours_start' => $store->business_hours_start ?? '',
                                        'business_hours_end' => $store->business_hours_end ?? '',
                                        'aptitude_imgs' => [],
                                        'dispatch_type' => [],
                                        'affiche' => $store->affiche ?? '',
                                        'user_uid' => $store->user_uid ?? 0,
                                        'information' => $store->information ?? '',
                                        'is_black' => 0,
                                        'banner_thumb' => '',
                                        'is_hide' => $store->is_hide ?? 0,
                                        'specify_show' => $store->specify_show ?? 0,
                                        'operating_state' => $store->operating_state ?? 0,
                                        'boss_uid' => 0,
                                        'audio_open' => 0,
                                        'initials' => '',
                                        'validity' => 0,
                                        'validity_status' => 0,
                                        'id_card_imgs' => ['', ''],
                                        'other_imgs' => [],
                                        'yun_horn' => '',
                                        'zkc_pay' => null,
                                        'salt' => null,
                                        'home_store_url' => null,
                                        'goods_store_url' => null,
                                        'collect_money_url' => null,
                                        'payment_jump_minapp' => null,
                                        'payment_jump_h5' => null,
                                        'is_open_jump' => 0,
                                        'separate_payment_jump_minapp' => null,
                                        'separate_payment_jump_h5' => null,
                                        'balance_id' => 0,
                                        'platform_ids' => '',
                                        'settlement_num' => null,
                                        'settlement_type' => null,
                                        'recruiter_id' => 0
                                    ]
                                ]
                            ];
                        })->filter()->values()->toArray(),
                        'first_page_url' => $goods->url(1),
                        'from' => $goods->firstItem(),
                        'last_page' => $goods->lastPage(),
                        'last_page_url' => $goods->url($goods->lastPage()),
                        'next_page_url' => $goods->nextPageUrl(),
                        'path' => $goods->path(),
                        'per_page' => $goods->perPage(),
                        'prev_page_url' => $goods->previousPageUrl(),
                        'to' => $goods->lastItem(),
                        'total' => $goods->total()
                    ]
                ];
            }

            // 构建返回数据
            $data = [
                'store_id'             => $store->id,
                'store_thumb'          => ImageUrlService::processImageUrl($store->thumb),
                'store_banner_thumb'   => '', // 该字段在表中不存在
                'store_name'           => $store->store_name,
                'operating_state'      => $store->operating_state ?? 0,
                'dispatch'             => '', // 该字段在表中不存在
                'dispatch_type'        => [], // 该字段在表中不存在
                'delivery_information' => '', // 该字段在表中不存在
                'affiche'              => $store->affiche ?? '',
                'comment'              => [
                    'total' => 0,
                    'score' => 0,
                    'list'  => []
                ],
                'goods_total'          => $store->storeGoods->count(),
                'order_count'          => 0,
                'business_hours'       => ($store->business_hours_start ?? '') . '-' . ($store->business_hours_end ?? ''),
                'store_address'        => $store->address ?? '',
                'store_mobile'         => $store->mobile ?? '',
                'store_introduce'      => $store->store_introduce ?? '',
                'lng'                  => $store->longitude ?? 0,
                'lat'                  => $store->latitude ?? 0,
                'specify_show'         => $store->specify_show ?? 0,
                'is_open_cashier'     => 0, // 该字段在表中不存在
                'store_carry'          => [
                    'name'   => '提货人姓名',
                    'number' => '提货人手机'
                ],
                'store_delivery'       => [
                    'delivery_status' => 0,
                    'delivery_note'   => '',
                    'delivery_area'   => '',
                    'locations'       => [
                        'longitude' => $store->longitude ?? 0,
                        'latitude'  => $store->latitude ?? 0
                    ],
                    'delivery_amount' => 0
                ],
                'need_lat'             => 0,
                'lat_data'             => [],
                'logo_style'           => 0,
                'first_category'       => $firstCategoryData,
                'category'             => $category ? [
                    'id'   => $category->id,
                    'name' => $category->name
                ] : null
            ];

            return response()->json([
                'code' => 200,
                'message' => '获取成功',
                'data' => $data
            ]);

        } catch (Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '获取失败: ' . $e->getMessage(),
                'data' => null
            ]);
        }
    }

    /**
     * 获取商家列表
     */
    public function index(Request $request)
    {
        try {
            $page = $this->getParam($request, 'page', 1);
            $limit = $this->getParam($request, 'limit', 10);

            $stores = Store::with('category')
                ->where('is_hide', 0)
                ->paginate($limit, ['*'], 'page', $page);

            return response()->json([
                'code' => 200,
                'message' => '获取成功',
                'data' => $stores
            ]);

        } catch (Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '获取失败: ' . $e->getMessage(),
                'data' => null
            ]);
        }
    }

    /**
     * 搜索商家
     */
    public function search(Request $request)
    {
        try {
            $keyword = $this->getParam($request, 'keyword');
            $page = $this->getParam($request, 'page', 1);
            $limit = $this->getParam($request, 'limit', 10);

            if (!$keyword) {
                return response()->json([
                    'code' => 400,
                    'message' => '搜索关键词不能为空',
                    'data' => null
                ]);
            }

            $stores = Store::with('category')
                ->where('is_hide', 0)
                ->where(function($query) use ($keyword) {
                    $query->where('store_name', 'like', "%{$keyword}%")
                          ->orWhere('address', 'like', "%{$keyword}%");
                })
                ->paginate($limit, ['*'], 'page', $page);

            return response()->json([
                'code' => 200,
                'message' => '搜索成功',
                'data' => $stores
            ]);

        } catch (Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '搜索失败: ' . $e->getMessage(),
                'data' => null
            ]);
        }
    }
}
